package xcmg.device.service.warehouse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.warehouse.DepartmentWarehouseRelationDO;
import xcmg.device.dao.entity.warehouse.EnableWarehouseControlDO;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.dao.mapper.warehouse.DepartmentWarehouseRelationMapper;
import xcmg.device.dao.mapper.warehouse.EnableWarehouseControlMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDOMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.vo.permission.WareHousePermission;
import xcmg.device.service.vo.warehouse.AddDepartmentWarehouseVO;
import xcmg.device.service.vo.warehouse.DepartmentWareHouseRelationQueryListVO;
import xcmg.device.service.vo.warehouse.DepartmentWarehouseRelationVO;
import yb.ecp.fast.feign.FastGenClient;

import java.util.*;

/**
 * Created by wrg on 2019/5/20.
 */
@Service
public class DepartmentWarehouseRelationService {
    @Autowired
    private DepartmentWarehouseRelationMapper relationMapper;
    @Autowired
    private FastGenClient genClient;
    @Autowired
    private EnableWarehouseControlMapper controlMapper;
    @Autowired
    private WarehouseDOMapper warehouseDOMapper;

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(AddDepartmentWarehouseVO addVO) throws Exception {
        //校验是否启用
        String departmentId = addVO.getDepartmentId();
        String orgId = addVO.getOrgId();
        addDel(departmentId, orgId);
        List<DepartmentWarehouseRelationVO> warehouseRelationVOList = addVO.getWarehouseRelationVOList();
        for (DepartmentWarehouseRelationVO relationVO : warehouseRelationVOList) {
            boolean check = relationVO.isCheck();
            if (!check){
                continue;
            }
            DepartmentWarehouseRelationDO record = new DepartmentWarehouseRelationDO();
            record.setDepartmentId(departmentId);
            record.setOrgId(orgId);
            record.setWarehouseCode(relationVO.getWarehouseCode());
            record.setWarehouseId(relationVO.getWarehouseId());
            //新老接口切换，因为控制库存的字段是新增的，为了防止切换的时候有人调用老接口保存，所以在这里设置WarehouseInvertoryControl为1
            record.setWarehouseInvertoryControl(1);
            String id = genClient.newGuidText().getValue();
            if (StringUtils.isBlank(id)) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
            record.setId(id);
            int insertCount = relationMapper.insertSelective(record);
            if (insertCount <= 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }


    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(List<DepartmentWarehouseRelationDO> relations,String orgId,String departmentId) throws Exception {
        //校验是否启用
        addDel(departmentId, orgId);
        for (DepartmentWarehouseRelationDO relation : relations) {
            String id = genClient.newGuidText().getValue();
            if (StringUtils.isBlank(id)) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
            relation.setOrgId(orgId);
            relation.setDepartmentId(departmentId);
            relation.setId(id);
            int insertCount = relationMapper.insertSelective(relation);
            if (insertCount <= 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }


    private boolean addDel(String departmentId, String orgId) throws Exception {
       return relationMapper.delete(departmentId,orgId) > 0;
    }

    public ErrorCode addIsEnable(Integer isEnable,String departmentId, String orgId) throws Exception {
        EnableWarehouseControlDO data = controlMapper.getData(departmentId, orgId);
        if (null == data) {
            String controlId = genClient.newGuidText().getValue();
            if (StringUtils.isBlank(controlId)) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }

            EnableWarehouseControlDO record = new EnableWarehouseControlDO();
            record.setId(controlId);
            record.setIsEnable(isEnable);
            record.setOrgId(orgId);
            record.setDepartmentId(departmentId);
            int i = controlMapper.insertSelective(record);
            if (i < 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
            return  ErrorCode.Success;
        }

        EnableWarehouseControlDO updateDate = new EnableWarehouseControlDO();
        updateDate.setIsEnable(isEnable);
        updateDate.setId(data.getId());
       return controlMapper.updateByPrimaryKeySelective(updateDate) > 0 ?ErrorCode.Success:ErrorCode.Failure;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode del(List<String> ids) throws Exception {
        for (String id : ids) {
            int delCount = relationMapper.deleteByPrimaryKey(id);
            if (delCount <= 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }
        return ErrorCode.Success;
    }

    /**
     * @Des 是否具有仓库库存权限，如果没有开启仓库库存权限配置则有全部仓库的权限，
     * 如果开启仓库库存权限，查询配置的可以查看的仓库，如果没有配置则返回没有权限擦和讯，如果配置了则返回配置的仓库编码
     * @Date 2020/11/3 11:17
     * @Author wangzhaoyu
     * @Param []
     * @Return xcmg.device.service.vo.permission.WareHousePermission
     */
    public WareHousePermission hasWarehouseInveryControPermisson(String orgId, String departmentId){
        WareHousePermission result = new WareHousePermission();
        boolean exist = verifyThatPermissionsExist(departmentId, orgId);
        //没有配置仓库控制直接返回true，说明没有限制，代表有所有权限
        if(!exist){
            result.setHasPermission(true);
            result.setPermissionWarehouses(null);
            return result;
        }
        List<String> warehouseList = getWarehouse(departmentId, orgId);
        if(CollectionUtils.isEmpty(warehouseList)){
            result.setHasPermission(false);
            return result;
        }
        result.setHasPermission(true);
        result.setPermissionWarehouses(warehouseList);
        return result;
    }



    /**
     *@Description 是否有仓库权限，如果没有开启仓库控制则有全部的权限，查询不添加额外限制条件
     * 如果仓库控制开启查询是否配置了可以访问的仓库，如果没有配置则返回没有权限查询，如果配置了则把查询条件拼接查询条件
     *@Author wzy
     *@Date 2020/8/24
     *@Time 11:25
     */
    public WareHousePermission hasMajorWareHousePermission(String orgId, String departmentId){
        WareHousePermission result = new WareHousePermission();
        boolean exist = verifyThatPermissionsExist(departmentId,orgId);
        if(!exist){//没有配置仓库控制直接返回true，说明没有限制，代表有所有权限
            result.setHasPermission(true);
            result.setPermissionWarehouses(null);
            return result;
        }
        List<String> warehouseList = getMajorControl(departmentId, orgId);
        if (warehouseList.isEmpty()){
            result.setHasPermission(false);
            return result;
        }
        result.setHasPermission(true);
        result.setPermissionWarehouses(warehouseList);
        return result;
    }

    /**
    *@Description 获取有权限查看的仓库码(主库区+次库区)
    *@Author wzy
    *@Date 2020/8/29
    *@Time 17:27
    */
    public WareHousePermission wareHouseChoicePermit(String orgId, String departmentId){
        //判断是否开启了控制，如果没有开启，直接返回true
        WareHousePermission result = new WareHousePermission();
        boolean exist = verifyThatPermissionsExist(departmentId,orgId);
        if(!exist){//没有配置仓库控制直接返回true，说明没有限制，代表有所有权限
            result.setHasPermission(true);
            result.setPermissionWarehouses(null);
            return result;
        }
        //获取主库区配置+次库区配置，如果都没有配置，则没有权限
        List<String> majorControl = getMajorControl(departmentId, orgId);
        List<String> minorControl = getMinorControl(departmentId, orgId);
        if(CollectionUtils.isEmpty(majorControl) && CollectionUtils.isEmpty(minorControl)){
            result.setHasPermission(false);
            return result;
        }
        Set<String> resultSet = new HashSet<>();
        resultSet.addAll(majorControl);
        resultSet.addAll(minorControl);
        result.setHasPermission(true);
        result.setPermissionWarehouses(new ArrayList<>(resultSet));
        return result;

    }

    public boolean verifyThatPermissionsExist(String departmentId, String orgId) {
        return controlMapper.checkIsEnable(departmentId, orgId) > 0;
    }

    public List<String> getWarehouse(String departmentId, String orgId) {
        List<DepartmentWarehouseRelationDO> relationDOS = relationMapper.selectInvertoryContByDeptWare(departmentId, orgId);
        List<String> resultList = new ArrayList<>();
        if (!relationDOS.isEmpty()) {
            relationDOS.forEach(x -> {
                resultList.add(x.getWarehouseCode());
            });
        }
        return resultList;
    }
    /**
    *@Description 获取主库区控制配置 //TODO wzy递归查询自己和子部门的配置
    *@Author wzy
    *@Date 2020/8/24
    *@Time 17:39
    */
    public List<String> getMajorControl(String departmentId, String orgId){
        List<DepartmentWarehouseRelationDO> relationDOS = relationMapper.selectMajorControlByDeptWare(departmentId, orgId);
        List<String> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(relationDOS)) {
            relationDOS.forEach(x -> {
                resultList.add(x.getWarehouseCode());
            });
        }
        return resultList;
    }

    /**
    *@Description 获取次库区的控制 //TODO wzy 递归查询自己和子部门的配置
    *@Author wzy
    *@Date 2020/8/29
    *@Time 17:18
    */
    public List<String> getMinorControl(String departmentId, String orgId){
        List<DepartmentWarehouseRelationDO> relationDOS = relationMapper.selectMinorControlByDeptWare(departmentId, orgId);
        List<String> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(relationDOS)) {
            relationDOS.forEach(x -> {
                resultList.add(x.getWarehouseCode());
            });
        }
        return resultList;
    }

    public List<DepartmentWarehouseRelationVO> queryWarehouseList(String departmentId, String orgId) {
        List<DepartmentWarehouseRelationVO> voList = new ArrayList<>();
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.list(null, null, orgId, null,null,null,null,null);
        warehouseDOS.forEach(x -> {
            String description = x.getDescription();
            String id = x.getId();
            String warehouseCode = x.getWarehouseCode();
            DepartmentWarehouseRelationVO vo = new DepartmentWarehouseRelationVO();
            vo.setDescription(description);
            vo.setWarehouseId(id);
            vo.setWarehouseCode(warehouseCode);

            DepartmentWarehouseRelationDO record = new DepartmentWarehouseRelationDO();
            record.setWarehouseId(id);
            record.setOrgId(orgId);
            record.setDepartmentId(departmentId);
            vo.setCheck( relationMapper.checkWarehouseInvertoryCont(record) > 0);
            voList.add(vo);
        });

        return voList;
    }

    /**
    *@Description 企业空间-->组织结构-->仓库配置查询
    *@Author wzy
    *@Date 2020/8/24
    *@Time 15:51
    */
    public DepartmentWareHouseRelationQueryListVO queryWarehouseListV2(String departmentId, String orgId) {
        //仓库库存控制集合
        List<DepartmentWarehouseRelationVO> warehouseRelationVOList = new ArrayList<>();
        //主库区控制集合
        List<DepartmentWarehouseRelationVO> majorControls = new ArrayList<>();
        //次库区控制集合
        List<DepartmentWarehouseRelationVO> minorControls = new ArrayList<>();
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.list( null, null, orgId,null,null,null,null,null);
        warehouseDOS.forEach(x->{
            String description = x.getDescription();
            String id = x.getId();
            String warehouseCode = x.getWarehouseCode();
            //仓库库存控制
            DepartmentWarehouseRelationVO wareHouseInvoteryControl = new DepartmentWarehouseRelationVO(description,id,warehouseCode);
            //主库区控制数据
            DepartmentWarehouseRelationVO majorControl = new DepartmentWarehouseRelationVO(description,id,warehouseCode);
            //次库区控制数据
            DepartmentWarehouseRelationVO minorControl = new DepartmentWarehouseRelationVO(description,id,warehouseCode);

            //查询仓库控制配置
            DepartmentWarehouseRelationDO record = new DepartmentWarehouseRelationDO();
            record.setWarehouseId(id);
            record.setOrgId(orgId);
            record.setDepartmentId(departmentId);
            List<DepartmentWarehouseRelationDO> departmentWarehouseRelations = relationMapper.selectByDeptIdAndOrgId(record);

            //拼接仓库配置
            if(CollectionUtils.isEmpty(departmentWarehouseRelations)){
                wareHouseInvoteryControl.setCheck(false);
                majorControl.setCheck(false);
                minorControl.setCheck(false);
            }else{
                DepartmentWarehouseRelationDO relationDO = departmentWarehouseRelations.get(0);
                Integer warehouseInvertory = relationDO.getWarehouseInvertoryControl();
                Integer documnetMajor = relationDO.getDocumnetMajorControl();
                Integer documentMinor = relationDO.getDocumentMinorControl();
                boolean warehouseInvertoryCheck = warehouseInvertory == null || warehouseInvertory.compareTo(1) != 0
                        ? false : true;
                wareHouseInvoteryControl.setCheck(warehouseInvertoryCheck);
                boolean documnetMajorCheck = documnetMajor == null || documnetMajor.compareTo(1) != 0
                        ? false : true;
                majorControl.setCheck(documnetMajorCheck);
                boolean documentMinorCheck = documentMinor == null || documentMinor.compareTo(1) != 0
                        ? false : true;
                minorControl.setCheck(documentMinorCheck);
            }
            warehouseRelationVOList.add(wareHouseInvoteryControl);
            majorControls.add(majorControl);
            minorControls.add(minorControl);
        });
        DepartmentWareHouseRelationQueryListVO result = new DepartmentWareHouseRelationQueryListVO();
        result.setWarehouseRelationVOList(warehouseRelationVOList);
        result.setMajorControls(majorControls);
        result.setMinorControls(minorControls);
        return result;
    }

    public Integer getIsEnableStatus(String departmentId, String orgId) {
        EnableWarehouseControlDO data = controlMapper.getData(departmentId, orgId);
        if (null == data){
            return 0;
        }
        return data.getIsEnable();
    }
}
